﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Windows.Forms;

namespace PostMedia
{
	public class SmartTextBox : TextBox
	{
		private bool _noteVisible;
		private char _passwordChar;
		private bool _ignoreChange;
		private Color _foreColor;
		private string _note;

		public SmartTextBox()
		{
			_note = "Some note";
			_foreColor = base.ForeColor;			
			_noteVisible = true;
			SetNoteColor();
			base.Text = _note;
		}

		public new string Text
		{
			get
			{
				if (_noteVisible)
					return "";
				return base.Text;
			}
			set
			{
				base.Text = value;
			}
		}

		public string Note
		{
			get
			{
				return _note;
			}
			set
			{
				_note = value;
				if (_noteVisible)
					base.Text = value;
			}
		}

		public new Color ForeColor
		{
			get
			{
				return _foreColor;
			}
			set
			{
				_foreColor = value;
				if (_noteVisible)
					SetNoteColor();
				else
					base.ForeColor = value;
			}
		}

		public new Color BackColor
		{
			get
			{
				return base.BackColor;
			}
			set
			{
				base.BackColor = value;
				if (_noteVisible)
					SetNoteColor();
			}
		}

		public new char PasswordChar
		{
			get
			{
				return _passwordChar;
			}
			set
			{
				_passwordChar = value;
				if (base.PasswordChar != '\0')
					base.PasswordChar = value;
			}
		}

		private void SetNoteColor()
		{
			Color f = _foreColor;
			Color b = base.BackColor;
			Color n = Color.FromArgb((f.R + b.R) / 2, (f.G + b.G) / 2, (f.B + b.B) / 2);
			base.ForeColor = n;
		}

		protected override void OnMouseDown(MouseEventArgs e)
		{
			base.OnMouseDown(e);

			if (_noteVisible)
				base.Select(0, 0);
		}

		protected override void OnMouseMove(MouseEventArgs e)
		{
			base.OnMouseMove(e);

			if (_noteVisible)
				base.Select(0, 0);
		}

		protected override void OnKeyDown(KeyEventArgs e)
		{
			base.OnKeyDown(e);

			if (_noteVisible)
			{
				if (e.KeyCode == Keys.Back || e.KeyCode == Keys.Escape)
					return;

				_ignoreChange = true;
				base.Text = "";
				base.ForeColor = _foreColor;
				_ignoreChange = false;
				base.PasswordChar = _passwordChar;
				_noteVisible = false;
			}
		}

		protected override void OnLostFocus(EventArgs e)
		{
			base.OnLostFocus(e);

			ChangeToNoteIfNeeded();
		}

		protected override void OnTextChanged(EventArgs e)
		{
			base.OnTextChanged(e);

			if (_ignoreChange)
				return;

			ChangeToNoteIfNeeded();
		}

		private void ChangeToNoteIfNeeded()
		{
			if (!_noteVisible)
			{
				if (base.TextLength == 0)
				{
					_ignoreChange = true;
					base.Text = "";
					base.PasswordChar = '\x0';
					SetNoteColor();
					base.Text = _note;
					_ignoreChange = false;
					_noteVisible = true;
				}
			}
		}

	}
}
